<script>
  import { login } from "../../api";
  import { navigate } from "svelte-routing";

  let username = "admin";
  let password = "123456";
  export let error = "";

  function handleLogin() {
    if (login(username, password)) {
      const params = new URLSearchParams(window.location.search);
      const redirect = params.get("redirect") || "/";
      navigate(redirect);
    } else {
      error = "用户名或密码错误";
    }
  }
</script>

<div class="max-w-md mx-auto h-full flex justify-center items-center">
  <div
    class="max-w-md w-full px-4 py-2 shadow-md rounded-lg bg-white dark:bg-gray-800"
  >
    <h1 class="text-2xl font-bold mb-6">登录</h1>

    {#if error}
      <div
        class="bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-800 text-red-700 dark:text-red-300 px-4 py-3 rounded mb-4"
      >
        {error}
      </div>
    {/if}

    <div class="mb-4">
      <label for="username" class="block mb-2">用户名</label>
      <input
        id="username"
        type="text"
        autocomplete="off"
        bind:value={username}
        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
      />
    </div>

    <div class="mb-6">
      <label for="password" class="block mb-2">密码</label>
      <input
        id="password"
        type="password"
        autocomplete="off"
        bind:value={password}
        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
      />
    </div>

    <button
      on:click={handleLogin}
      class="w-full px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
    >
      登录
    </button>

    <div class="mt-4 text-center text-sm text-gray-500 dark:text-gray-400">
      <p>测试账号:</p>
      <p>普通用户: user / user</p>
      <p>管理员: admin / admin</p>
    </div>
  </div>
</div>
